package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    // 发送短信
    @Override
    public void sendMsg(String phone) {
        // 1.生成六位随机数
        String code =RandomUtil.randomNumbers(6);
        code = "123"; // TODO 开发期间写死
        // 2.调用阿里云sms发短信
        // smsTemplate.sendSms(phone, code);   // TODO 开发期间注释
        // 3.将验证码存入redis （5分钟）
        redisTemplate.opsForValue().set("code:"+phone,code , Duration.ofSeconds(300) );
    }




    // 登录注册
    @Override
    public ResultInfo login(String phone, String code) {
        // 1.比较验证码是否正确
        // 1-1 取出redis
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:" + phone);
        // 1-2 比较
        if (!StrUtil.equals(code, codeFromRedis)) {
            // throw new ClassCastException("验证码不正确");
            return ResultInfo.error("验证码不正确");
        }
        // 2.根据手机查询数据库
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));

        if (user == null) {  // 3.新用户
            // 帮他注册
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        } else { // 4.老用户
            // 校验状态
            if (user.getStatus()!=1) {
                return ResultInfo.error("此用户已冻结，请联系企业");
            }
        }

        // 5.jwt制作token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());
        String token = JwtUtil.createToken(claims);
        // 6.将user存redis
        redisTemplate.opsForValue().set("phone:"+user.getPhone(), user, Duration.ofDays(1));
        // 7.清除redis中验证码
        redisTemplate.delete("code:" + phone);
        // 8.返回token
        return ResultInfo.success(token);
    }


}
